import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class BaseSelectBirthDay extends StatefulWidget {
  /// 选中的时间
  final String selectedDate;

  /// 默认公历
  final bool isGregorian;

  /// 结果返回
  final Function(bool isGregorian, String date) onSelectedDate;

  const BaseSelectBirthDay({Key key, this.selectedDate, this.onSelectedDate, this.isGregorian = true}) : super(key: key);

  @override
  _BaseSelectBirthDayState createState() => _BaseSelectBirthDayState();
}

class _BaseSelectBirthDayState extends State<BaseSelectBirthDay> {
  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor;

  bool _isGregorian = true;

  //每列的宽度
  double get _columnWidth => MediaQuery.of(context).size.width / 3;

  static final double _itemHeight = 48;

  //年数组
  List<String> _yearList = [];

  //月数组
  List<String> _monthList = [];

  //天数组
  List<String> _dayList = [];

  //年的索引
  int yearIndex;

  //月的索引
  int monthIndex;

  //天的索引
  int dayIndex;
  FixedExtentScrollController yearScrollController;
  FixedExtentScrollController monthScrollController;
  FixedExtentScrollController dayScrollController;

  void initState() {
    super.initState();
    if (widget.isGregorian != null) _isGregorian = widget.isGregorian;
    _setupData();
    _initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController.dispose();
    monthScrollController.dispose();
    dayScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 8),
      child: Column(
        children: [
          _buildHead(),
          BaseComponentUtils.buildHorizontalDivider(),
          Expanded(child: _buildDatePicker()),
        ],
      ),
    );
  }

  Widget _buildDatePicker() {
    Size label = BaseUtils.boundingTextSize(context, '年', TextStyle(color: Colors.grey, fontSize: 16));
    return Container(
      color: Colors.white,
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return Stack(
            children: [
              Row(
                children: <Widget>[
                  Expanded(child: _buildYearPickerView()),
                  Expanded(child: _monthPickerView()),
                  Expanded(child: _dayPickerView()),
                ],
              ),
              IgnorePointer(child: Container(color: Color(0xFFD1D1D6), margin: EdgeInsets.only(top: constraints.maxHeight / 2 - _itemHeight / 2), height: 1)),
              IgnorePointer(child: Container(color: Color(0xFFD1D1D6), margin: EdgeInsets.only(top: constraints.maxHeight / 2 + _itemHeight / 2), height: 1)),
              IgnorePointer(
                child: Container(
                  margin: EdgeInsets.only(top: constraints.maxHeight / 2 - _itemHeight / 2 + label.height / 2),
                  child: Row(
                    children: [
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(left: _columnWidth - 50),
                          child: Text('年', style: TextStyle(color: Colors.grey, fontSize: 16), maxLines: 1),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(left: _columnWidth - 60),
                          child: Text('月', style: TextStyle(color: Colors.grey, fontSize: 16), maxLines: 1),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(left: _columnWidth - 60),
                          child: Text('日', style: TextStyle(color: Colors.grey, fontSize: 16), maxLines: 1),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildYearPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: yearScrollController,
        children: _buildYearWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            yearIndex = index;
          });
          _updateDayList();
        },
        itemExtent: _itemHeight,
      ),
    );
  }

  ///月
  Widget _monthPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: monthScrollController,
        children: _buildMonthWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            monthIndex = index;
          });
          _updateDayList();
        },
        itemExtent: 44,
      ),
    );
  }

  ///日
  Widget _dayPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: dayScrollController,
        children: _buildDayWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            dayIndex = index;
          });
        },
        itemExtent: 44,
      ),
    );
  }

  ///年Widget
  List<Widget> _buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in _yearList) {
      yearListWidget.add(Center(child: Text(item, style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> _buildMonthWidget() {
    List<Widget> monthListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in _monthList) {
      monthListWidget.add(Center(child: Text(item, style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return monthListWidget;
  }

  ///日Widget
  List<Widget> _buildDayWidget() {
    List<Widget> dayListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in _dayList) {
      dayListWidget.add(Center(child: Text(item, style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return dayListWidget;
  }

  Widget _buildHead() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 4),
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(onTap: _onCancelEvent, child: Text('取消', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14))),
          _buildLunarAndGregorian(title: '公历', isSelect: _isGregorian, event: () => _onLunarAndGregorianEvent(key: '0')),
          _buildLunarAndGregorian(title: '农历', isSelect: !_isGregorian, event: () => _onLunarAndGregorianEvent(key: '1')),
          InkWell(onTap: _onConfirmEvent, child: Text('确认', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14, color: systemColor, fontWeight: FontWeight.bold))),
        ],
      ),
    );
  }

  Widget _buildLunarAndGregorian({@required String title, @required bool isSelect, @required Function event}) {
    return InkWell(
      onTap: event,
      child: Row(
        children: [
          Container(
            width: 18.0,
            height: 18.0,
            decoration: BoxDecoration(shape: BoxShape.circle, color: isSelect ? systemColor : Colors.white, border: Border.all(color: isSelect ? systemColor : Color(0xFF868686))),
            child: Icon(BaseIconData.x3Checked, size: 12, color: isSelect ? Colors.white : Colors.transparent),
          ),
          SizedBox(width: 4),
          Text(title, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14, color: isSelect ? systemColor : Color(0xFF868686))),
        ],
      ),
    );
  }

  /// 公历、农历选择事件
  void _onLunarAndGregorianEvent({@required String key}) {
    if (key == '0') _isGregorian = true;
    if (key == '1') _isGregorian = false;
    setState(() {});
  }

  ///选中年月后更新天
  void _updateDayList() {
    // int year = int.parse(_yearList[yearIndex]);
    // int month = int.parse(_monthList[monthIndex]);

    // setState(() {
    //   dayIndex = 0;
    //   _dayList = _getDayList(year: year, month: month);
    //   // ignore: invalid_use_of_protected_member
    //   if (dayScrollController.positions.length > 0) {
    //     dayScrollController.jumpTo(0);
    //   }
    // });
  }

  ///初始化数据
  void _setupData() {
    for (int i = 1970; i <= DateTime.now().year; i++) {
      _yearList.add(i.toString());
    }

    for (int i = 1; i <= 12; i++) {
      _monthList.add(i.toString().padLeft(2, '0'));
    }

    // 初始化天数(当前时间系统时间的天数)
    int year = DateTime.now().year;
    int month;
    if (widget.selectedDate == null || widget.selectedDate.isEmpty) {
      month = DateTime.now().month;
    } else {
      List<String> date = widget.selectedDate.split('-');
      month = int.parse(date[1]);
    }

    _dayList = _getDayList(year: year, month: month);
  }

  int _getDayCount({int year, int month}) {
    int dayCount = DateTime(year, month + 1, 0).day;
    return dayCount;
  }

  List<String> _getDayList({int year, int month}) {
    List<String> dayList = [];
    int days = _getDayCount(year: year, month: month);
    for (int i = 1; i <= days; i++) {
      dayList.add(i.toString().padLeft(2, '0'));
    }

    return dayList;
  }

  ///初始化时间索引
  void _initSelectedIndex() {
    final List uniqueYearList = Set.from(_yearList).toList();
    final List uniqueMonthList = Set.from(_monthList).toList();
    final List uniqueDayList = Set.from(_dayList).toList();

    ///获取索引
    if (widget.selectedDate != null && widget.selectedDate.isNotEmpty) {
      ///传了选中日期的时候
      List<String> date = widget.selectedDate.split('-');

      setState(() {
        yearIndex = uniqueYearList.indexOf(date[0]);
        monthIndex = uniqueMonthList.indexOf(date[1]);
        dayIndex = uniqueDayList.indexOf(date[2]);
      });
    } else {
      ///没有传选中日期默认当前系统时间
      String year = DateTime.now().year.toString();
      String month = DateTime.now().month.toString().padLeft(2, '0');
      String day = DateTime.now().day.toString().padLeft(2, '0');

      setState(() {
        yearIndex = uniqueYearList.indexOf(year);
        monthIndex = uniqueMonthList.indexOf(month);
        dayIndex = uniqueDayList.indexOf(day);
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    monthScrollController = FixedExtentScrollController(initialItem: monthIndex);
    dayScrollController = FixedExtentScrollController(initialItem: dayIndex);
  }

  /// 取消
  void _onCancelEvent() {
    BaseRouterUtil.getInstance().pop();
  }

  /// 确认事件
  void _onConfirmEvent() {
    if (widget.onSelectedDate != null) {
      String date = _yearList[yearIndex] + '-' + _monthList[monthIndex] + '-' + _dayList[dayIndex];
      widget.onSelectedDate(_isGregorian, date);
    }
    BaseRouterUtil.getInstance().pop();
  }
}
